#include <brpc/server.h>
#include <butil/logging.h>

#include "logger.hpp"
#include "etcd.hpp"
#include "utils.hpp"

#include "file.pb.h"
#include "base.pb.h"

namespace im
{
    class FileServiceImpl : public FileService{
    public:
        FileServiceImpl(const std::string &storage_path):
            _storage_path(storage_path){
            umask(0);
            mkdir(storage_path.c_str(), 0775);
            if (_storage_path.back() != '/') _storage_path.push_back('/');
        }
        virtual void GetSingleFile(google::protobuf::RpcController* controller,
                       const im::GetSingleFileReq* request,
                       im::GetSingleFileRsp* response,
                       google::protobuf::Closure* done){
            LOG_INFO("收到来自 {} 的 获取单个文件 请求", request->request_id());
            brpc::ClosureGuard rpc_guard(done);
            // 取出请求中的文件ID（其实就是文件名）
            std::string fid = request->file_id();
            std::string fileName = _storage_path + fid;
            std::string content;
            if(readFile(fileName, content) == false){
                response->set_success(false);
                response->set_errmsg(fileName + "文件读取失败");
                LOG_CRITICAL("{} 文件读取失败: {}", fid, fileName);
                return ;
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
            response->set_errmsg("");
            response->mutable_file_data()->set_file_id(fid);
            response->mutable_file_data()->set_file_content(content);
        }
        virtual void GetMultiFile(google::protobuf::RpcController* controller,
                       const im::GetMultiFileReq* request,
                       im::GetMultiFileRsp* response,
                       google::protobuf::Closure* done){
            LOG_INFO("收到来自 {} 的 获取多个文件 请求", request->request_id());
            brpc::ClosureGuard rpc_guard(done);
            for(auto file_id : request->file_id_list()){
                // 取出请求中的文件ID（起始就是文件名）
                std::string fid = file_id;
                std::string filename = _storage_path + fid;
                std::string content;
                if(readFile(filename, content) == false){
                    response->set_success(false);
                    response->set_errmsg("文件读取失败");
                    LOG_CRITICAL("{} 文件读取失败", fid);
                    return ;
                }
                FileDownloadData data;
                data.set_file_id(fid);
                data.set_file_content(content);
                response->mutable_file_data()->insert({fid, data});
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
            response->set_errmsg("");
        }
        virtual void PutSingleFile(google::protobuf::RpcController* controller,
                       const im::PutSingleFileReq* request,
                       im::PutSingleFileRsp* response,
                       google::protobuf::Closure* done){
            LOG_INFO("收到来自 {} 的 上传单个文件 请求", request->request_id());
            brpc::ClosureGuard rpc_guard(done);
            std::string fid = uuid();
            std::string fileName = _storage_path + fid;
            bool ret = writeFile(fileName, request->file_data().file_content());
            response->set_request_id(request->request_id());
            if(ret == false){
                response->set_success(false);
                response->set_errmsg("文件下载失败");
                LOG_CRITICAL("{} 文件下载失败", request->request_id());
                return;
            }
            response->set_success(true);
            response->set_errmsg("");
            response->mutable_file_info()->set_file_id(fid);
            response->mutable_file_info()->set_file_name(request->file_data().file_name());
            response->mutable_file_info()->set_file_size(request->file_data().file_size());
        }
        virtual void PutMultiFile(google::protobuf::RpcController* controller,
                       const im::PutMultiFileReq* request,
                       im::PutMultiFileRsp* response,
                       google::protobuf::Closure* done){
            LOG_INFO("收到来自 {} 的 上传多个文件 请求", request->request_id());
            brpc::ClosureGuard rpc_guard(done);
            response->set_request_id(request->request_id());
            response->set_success(true);
            response->set_errmsg("");
            for(auto file : request->file_data()){
                std::string fid = uuid();
                std::string fileName = _storage_path + fid;
                bool ret = writeFile(fileName, file.file_content());
                if(ret == false){
                    response->set_success(false);
                    response->set_errmsg("文件下载失败");
                    LOG_CRITICAL("{} 文件下载失败", request->request_id());
                    return;
                }
                auto newFile = response->add_file_info();
                newFile->set_file_id(fid);
                newFile->set_file_name(file.file_name());
                newFile->set_file_size(file.file_size());
            }
        }
        private:
        std::string _storage_path;
    };

    class FileServer{
    public:
        using ptr = std::shared_ptr<FileServer>;
        FileServer(const Registry::ptr& register_client, const std::shared_ptr<brpc::Server>& rpc_server)
            :_register_client(register_client), _rpc_server(rpc_server){}

        void start(){
            _rpc_server->RunUntilAskedToQuit();
        }
    private:
        Registry::ptr _register_client;
        std::shared_ptr<brpc::Server> _rpc_server;
    };

    class FileServerBuild{
    public:
        FileServerBuild(){}

        void init_register_client(const std::string& reg_host, const std::string& service_name, const std::string& access_host){
            _register_client = std::make_shared<Registry>(reg_host);        // 登入IP
            _register_client->register_server(service_name, access_host);   // 注册服务
        }

        void init_rpc_server(uint16_t port, int32_t timeout, uint8_t num_threads, const std::string &path = "./data/"){
            _rpc_server = std::make_shared<brpc::Server>();
            FileServiceImpl *file_service = new FileServiceImpl(path);
            _rpc_server->AddService(file_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);

            brpc::ServerOptions opt;
            opt.idle_timeout_sec = timeout;
            opt.num_threads = num_threads;

            if(_rpc_server->Start(port, &opt) != 0){
                LOG_CRITICAL("启动服务器失败！");
                abort();
            }
        }

        FileServer::ptr build(){
            if (!_register_client) {
                LOG_CRITICAL("还未初始化服务注册模块！");
                abort();
            }
            if (!_rpc_server) {
                LOG_CRITICAL("还未初始化RPC服务器模块! ");
                abort();
            }
            return std::make_shared<FileServer>(_register_client, _rpc_server);
        }
    private:
        Registry::ptr _register_client;
        std::shared_ptr<brpc::Server> _rpc_server;
    };
} // namespace im
